import portalCache from './portalCache';
import _ from 'lodash';
function _mergeMetaData(source, InstanceCode, isRun, subSystemCode) {
  return
  // const { ctx, app,config } = this;
  //变量合并
  let LocalVars = {};
  let styles = [];
  source.LocalVariables.forEach(item => {
    LocalVars[item.Code] = item.Value ? item.Value : item.DefaultValue;
  });
  //样式合并
  // if (source.Header.Style) {
  //   if (source.Header.Style.ClassList) styles.push(source.Header.Style.ClassList.join(''));
  //   styles.push(source.Header.Style.Style);
  // }
  if (source.Header.StyleSheet) {
    styles.push(source.Header.StyleSheet.StyleContent);
  }
  if (styles.length > 0) {
    let jsapi = window.document.createElement('link');
    jsapi.rel = 'stylesheet';
    jsapi.innerContent = styles.join('');
    window.document.head.appendChild(jsapi);
  }

  for (let key in source.ExtProperties) {
    LocalVars[key] = source.ExtProperties[key].Value;
  }

  source.PageParameters &&
    source.PageParameters.forEach(item => {
      LocalVars[item.Code] = item.Value ? item.Value : item.DefaultValue;
    });

  source.PageOutParameters &&
    source.PageOutParameters.forEach(item => {
      LocalVars[item.Code] = item.Value ? item.Value : item.DefaultValue;
    });

  //window.LocalVars[InstanceCode] = LocalVars

  // window.fasVueRootInstance.editData.LocalVars[InstanceCode] = LocalVars
  // window.fasVueRootInstance.$set(
  //   window.fasVueRootInstance.editData.LocalVars,
  //   InstanceCode,
  //   LocalVars,
  // );

  // if (isRun) {
  //   source.ViewModels.forEach(ucAction => {
  //     if (ucAction.ActionType == FASConst.ACTIONTYPE_SERVER) {
  //       window._fasSubSystemCodeMapping_.Action[ucAction.ActionID] =
  //         subSystemCode;
  //     } else if (ucAction.ActionType == FASConst.ACTIONTYPE_DQ) {
  //       window._fasSubSystemCodeMapping_.DQ[ucAction.ActionID] = subSystemCode;
  //     }
  //     let hasAction = window.pageMetaData.ViewModels.filter(
  //       pageAction => pageAction.ActionID == ucAction.ActionID,
  //     );
  //     if (!hasAction || hasAction.length == 0) {
  //       window.pageMetaData.ViewModels.push(ucAction);
  //       window.ActionList.push(ucAction);
  //       //需要处理
  //       dynamicRegistActionAndDQ(ucAction);
  //     }
  //   });
  // } else {
  //   // source.ViewModels.forEach(ucAction=>{
  //   //   let hasAction = window.pageMetaData.ViewModels.filter(pageAction=>pageAction.ActionID==ucAction.ActionID)
  //   //   if(!hasAction || hasAction.length == 0){
  //   //     window.pageMetaData.ViewModels.push(ucAction)
  //   //     //需要处理
  //   //   }
  //   // })
  // }

  //事件合并
  // if (source.bkEvents || source.ucPageMetadata.Events) {
  //   //let sourceEvents = replaceLocalVarsNS(replaceWidgetNS(source.Events,InstanceCode),InstanceCode)
  //   //只执行部件本身的事件，再内部的不处理
  //   let _bkEvents =
  //     source.bkEvents && source.bkEvents.length > 0
  //       ? source.bkEvents
  //       : source.ucPageMetadata.Events;
  //   let sourceEvents = replaceLocalVarsNS(
  //     replaceWidgetNS(_bkEvents, InstanceCode),
  //     InstanceCode,
  //   );

  //   if (isRun) {
  //     //交给部件自己处理
  //     pageLoad(sourceEvents, true);
  //     // 小部件的onloaded在门户组件内部触发
  //     //window.setTimeout(async ()=>{pageLoaded(sourceEvents,true,false)},0)
  //   }

  //   //
  //   //target.Events = target.Events.concat(sourceEvents)
  //   //需要处理
  // }
}
export const repreparePageContentForPortal = async function (
  id: string,
  isRun?: boolean,
  insCode?: string,
  isNotMerge?: boolean,
  subSystemCode?: string,
) {
  const pageContent: any = await getFasInstanceContextById(id, true);

  if (!pageContent) throw new Error('portlet metaData not exist！！！');
  const PMData = JSON.parse(pageContent.pageMetaData);
  return repreparePageContentForPortlet(
    pageContent,
    PMData,
    isRun,
    insCode,
    isNotMerge,
    subSystemCode,
  );
};
export async function repreparePageContentForPortlet(
  pageContent: any,
  PMData: object,
  isRun?: boolean,
  _insCode?: string,
  isNotMerge?: boolean,
  subSystemCode?: string,
) {
  if (!pageContent.ResourceUrl) {
    //@ts-ignore
    pageContent.ResourceUrl = '//' + window.TeldWebConfig.ResourceURL;
    pageContent.isCharts = false;
    pageContent.isRichText = false;
    pageContent.isExcelJS = false;
    pageContent.isReport = false;
    pageContent.isSelectHelper = false;
    pageContent.isPortal = true;
  }

  setFasCurrentInstance(pageContent);

  // if (!window.selectHelper) {
  //   await addInstanceScript('/fas/selectHelper.js');
  // }
  //let PMData = JSON.parse(pageContent.pageMetaData)

  let actions = [];
  PMData.ViewModels.forEach(item => {
    if (item.MethodContent) {
      actions.push(item.MethodContent);
    }
  });
  if (!PMData.bkEvents)
    PMData.bkEvents = JSON.parse(JSON.stringify(PMData.Events));
  else PMData.Events = JSON.parse(JSON.stringify(PMData.bkEvents));
  let Promises = [];
  let isPC = window.platform == 'pc';
  try {
    //安装依赖
    setupDependenciesScript();
    //安装词条
    setupTermScript(pageContent.i18nPageFile).then(() => {
      const event = new CustomEvent('fas:termLoaded', {
        detail: { PortalCode: PMData.Code },
      });
      window.dispatchEvent(event);
    });
  } catch (e) {}
  //页面名称
  if (pageContent.i18nPageNameKey) {
    let portletName = Funcs.GetTerms(
      pageContent.i18nPageNameKey,
      PMData.Name,
      PMData.Code,
    );
    PMData.Name = portletName;
  }

  //composePortletMeta()
  let ins = JSON.parse(JSON.stringify(metaTemplate));
  ins.ID = ins.CompID = Funcs.Guid();
  ins.ucPageMetadata = PMData;
  let insCode = _insCode ? _insCode : 'fas_portlet' + Funcs.Guid().substring(0, 6);
  if (!isNotMerge) _mergeMetaData(PMData, insCode, isRun, subSystemCode);
  ins.InstanceCode = ins.options.instanceCode = insCode;
  ins.options.target = {
    Name: PMData.Name,
    PortletPageSize: JSON.parse(PMData.ExtProperties.PortletPageSize.PropValue),
    hasValue: true,
    pageID: PMData.ID,
  };

  ins.options.inParams = [];
  let ParamTemplate = {
    ID: '',
    Code: '',
    Name: '',
    IsReadOnly: false,
    IsEnum: false,
    ValueType: 'String',
    Description: '',
    PropertyEditor: {
      PropertyEditorType: 3,
      ConfigJSON: null,
      Extends: {},
    },
    DefaultValue: '',
    IsRequired: false,
    PropType: 1,
    Level: 0,
    ParentID: '',
    ShowValue: '',
    Value: '',
    DisplayName: '',
    hide: false,
  };
  PMData.PageParameters.forEach(item => {
    let paramTemplate = JSON.parse(JSON.stringify(ParamTemplate));
    paramTemplate.ID = item.ID;
    paramTemplate.Code = item.Code;
    paramTemplate.ValueType = item.DataType;
    paramTemplate.DefaultValue = item.DefaultValue;
    paramTemplate.Name = item.Name;
    paramTemplate.ParamDescription = item.ParamDescription;
    paramTemplate.DisplayHelpSetting = item.DisplayHelpSetting;
    paramTemplate.HelpSetting = item.HelpSetting;
    paramTemplate.Value = item.ParamValue;
    paramTemplate.ParamType = item.ParamType;
    ins.options.inParams.push(paramTemplate);
  });
  return Promise.resolve(ins);
}
export function setFasCurrentInstance(ins) {
  return (window.currentFasInstanceContext = ins);
}
export function addInstanceScript(
  url: string,
  timeout?: number,
  id?: string,
  callback?: Function,
  useResource?: any,
) {
  let context = getFasCurrentInstance();
  let resourceUrl = useResource ? context.ResourceUrl + url : url;
  if (
    resourceUrl.startsWith('//') == false &&
    resourceUrl.startsWith('http') == false
  ) {
    resourceUrl = context.ResourceUrl + url;
  }
  return new Promise((resolve, reject) => {
    let jsapi = window.document.createElement('script');
    jsapi.src = resourceUrl;
    if (id) jsapi.id = id;
    jsapi.onload = function () {
      if (callback) callback();
      if (timeout && timeout > 0) {
        window.setTimeout(() => {
          resolve(null);
        }, timeout);
      } else {
        resolve(null);
      }
    };
    window.document.head.appendChild(jsapi);
  });
}
export async function setupTermScript(i18nPageFile) {
  //resource.teld7.top/telddoc/141/fascommonen-US.js?v=1686587311
  // let i18nPageFile = getFasCurrentInstance().i18nPageFile
  let teldLocale = window.readCookie('teld_locale');
  if (teldLocale && i18nPageFile.indexOf(teldLocale) == -1) {
    //语言和缓存不匹配了
    let s = i18nPageFile.split('?');
    let ns = s[0].replace(/.{8}$/, teldLocale + '.js');
    i18nPageFile = ns + '?' + s[1];
  }

  return addInstanceScript(i18nPageFile, null, null, null, false);
}

export function getFasCurrentInstance() {
  return window.currentFasInstanceContext;
}

export async function setupDependenciesScript() {
  return Promise.all([]);
}
window.getFasDevAppId = function () {
  var urlSplitList = window.location.href.replace(/https?:\/\//, '').split('/')
  if (urlSplitList && urlSplitList.length >= 3 && urlSplitList[1] != '#') {
    return urlSplitList[1]=='gencode'?urlSplitList[2]:urlSplitList[1]
  }
  return 'fas'
};
export async function getFasInstanceContextById(
  id: string,
  byId: boolean,
  url?: string,
) {
  let version = -1;
  let cacheData = portalCache.getRenderData(id);
  if (cacheData) {
    version = cacheData.version;
  }

  let fasDevAppId = window.getFasDevAppId();
  if (!url) {
    url =
      '//fas.teld.cc/' +
      fasDevAppId +
      '/get?' +
      (byId ? 'id' : 'code') +
      '=' +
      id;
    //url = "//" + fas.teld.cc + "/" + fasDevAppId + "/get?" + (byId ? 'id' : 'code') + "=" + id
  } else {
    url = url.replace('/render?', '/get?');
  }
  url += '&version=' + version;

  return new Promise((resolve, reject) => {
    window.getDataAsync(
      url,
      'get',
      {},
      function (ret) {
        //0代表没变
        if (ret && ret.version == 0) {
          resolve(cacheData);
        } else {
          portalCache.setRenderData(id, ret);
          resolve(ret);
        }
      },
      function () {
        reject();
      },
    );
  });
}

export async function repreparePageContentForPortal_v2(
  isExpired: boolean,
  id: string,
  isRun?: Boolean,
  insCode?: string,
  isNotMerge?: Boolean,
  subSystemCode?: string,
) {
  let startTime = performance.now();
  let pageContent = await getFasInstanceContextById_v2(isExpired, id, true);
  if (!pageContent) throw new Error('portlet metaData not exist！！！');
  let PMData = JSON.parse(pageContent.pageMetaData);

  return repreparePageContentForPortlet(
    pageContent,
    PMData,
    isRun,
    insCode,
    isNotMerge,
    subSystemCode,
  );
}
export async function getFasInstanceContextById_v2(
  isExpired: boolean,
  id,
  byId,
  url?: string,
) {
  let version = -1;
  let cacheData = portalCache.getRenderData(id);
  if (cacheData) {
    version = cacheData.version;
    if (false === isExpired) {
      if (cacheData instanceof Promise) {
        return cacheData;
      }
      return Promise.resolve(cacheData);
    }
  }
  return getFasInstanceContextById(id, byId, url);
}
export const IsPrecheckFasInstance = true;

export async function precheckFasInstance(portletInstances) {
  // let portletInstancesLocalCacheVersion =
  //   await getPortletInstancesLocalCacheVersion(portletInstances);
  // let expiredInstance = ''//await getFasInstanceCacheVersionById( portletInstancesLocalCacheVersion,);
  return [];
}
export async function getPortletInstancesLocalCacheVersion(portletInstances) {
  let PromiseList = [];
  var returnValue = portletInstances.map(ins => {
    let version = ''//getFasInstanceCacheVersion(ins.PageMetaDataID);
    PromiseList.push(version);
    return {
      pageId: ins.PageMetaDataID,
      version,
    };
  });
  let returnValueList = await Promise.all(PromiseList);
  returnValue.map((item, index) => {
    item.version = returnValueList[index];
  });
  return returnValue;
}
export async function getFasInstanceCacheVersionById(
  portletInstances,
  url?: string,
) {
  let fasDevAppId = window.getFasDevAppId();
  if (!url) {
    // url = "//localhost:9874/"+fasDevAppId+"/precheckFasInstance"
    url = '//' + location.host + '/' + fasDevAppId + '/precheckFasInstance';
  } else {
    url = url.replace('/render?', '/precheckFasInstance');
  }
  // url += ("&version="+ version)

  return new Promise((resolve, reject) => {
    window.getDataAsync(
      url,
      'post',
      {
        instanceList: portletInstances,
      },
      function (ret) {
        //0代表没变
        resolve(ret);
      },
      function () {
        reject();
      },
    );
  });
}
export let metaTemplate = {
  ID: '',
  MetaDataCode: 'fas-portlet',
  MetaDataName: '用户组件',
  Icon: 'icon-extend',
  ClientType: 2,
  CurrentVersion: '0.1.0.0',
  CompatibleMinVersion: '0.1.0.0',
  EngineVersion: '0.1.0.0',
  ExtOptions: {},
  StyleDesignerOption:
    'layout_widthAndHeight,layout_paddingAndMargin,opacity,position',
  FormMaking: null,
  Styles: [],
  Properties: [
    {
      ID: 'abe969ed-65ea-be24-0789-b0afc0e7a7d2',
      Code: 'InstanceCode',
      Name: '组件标识',
      IsReadOnly: false,
      IsEnum: false,
      IsRef: false,
      IsInternational: false,
      NeedSpecialTreatment: false,
      ValueType: 'String',
      Description: '组件标识',
      PropertyEditor: {
        PropertyEditorType: 0,
        ConfigJSON: null,
      },
      DefaultValue: 'NewInstanceID()',
      IsRequired: false,
      PropType: 3,
      Level: 0,
      ParentID: null,
      ShowValue: '',
      Value: 'NewInstanceID()',
      DisplayName: '',
    },
    {
      ID: 'aa09a297-b098-4a2e-8c4b-50ca2eaf5d01',
      Code: 'HideLabel',
      Name: '隐藏标题',
      IsReadOnly: false,
      IsEnum: false,
      IsRef: false,
      IsInternational: false,
      NeedSpecialTreatment: false,
      ValueType: 'Boolean',
      Description: '隐藏标题',
      PropertyEditor: {
        PropertyEditorType: 7,
        ConfigJSON: null,
      },
      DefaultValue: true,
      IsRequired: false,
      PropType: 0,
      Level: 0,
      ParentID: null,
      ShowValue: '',
      Value: true,
      DisplayName: '',
    },
    {
      ID: '569a7fb9-3a77-635b-d073-cbdaa570126b',
      Code: 'Visible',
      Name: '是否可见',
      IsReadOnly: false,
      IsEnum: false,
      IsRef: false,
      IsInternational: false,
      NeedSpecialTreatment: false,
      ValueType: 'Boolean',
      Description: '是否可见',
      PropertyEditor: {
        PropertyEditorType: 7,
        ConfigJSON: null,
      },
      DefaultValue: true,
      IsRequired: false,
      PropType: 3,
      Level: 0,
      ParentID: null,
      ShowValue: '',
      Value: true,
      DisplayName: '',
    },
    {
      ID: 'c0b446c4-3c3e-34a9-fe66-554fddef7b84',
      Code: 'Style',
      Name: '样式',
      IsReadOnly: false,
      IsEnum: false,
      IsRef: false,
      IsInternational: false,
      NeedSpecialTreatment: false,
      ValueType: 'Object',
      Description: '设置样式',
      PropertyEditor: {
        PropertyEditorType: 6,
        ConfigJSON: null,
      },
      DefaultValue: '',
      IsRequired: false,
      PropType: 1,
      Level: 0,
      ParentID: null,
      ShowValue: '',
      Value: '',
      DisplayName: '',
    },
    {
      ID: '2f8792d8-6214-f6c4-fb4d-334838a306be',
      Code: 'Target',
      Name: '用户组件',
      IsReadOnly: false,
      IsEnum: false,
      IsRef: false,
      IsInternational: false,
      NeedSpecialTreatment: false,
      ValueType: 'String',
      Description: '用户组件',
      PropertyEditor: {
        PropertyEditorType: 112,
        ConfigJSON: null,
      },
      DefaultValue: '',
      IsRequired: true,
      PropType: 1,
      Level: 0,
      ParentID: null,
      ShowValue: '',
      Value: '',
      DisplayName: '',
    },
    {
      ID: 'c9fb0f16-02b2-77d9-282f-c537d9d3d294',
      Code: 'InParams',
      Name: '入参',
      IsReadOnly: false,
      IsEnum: false,
      IsRef: false,
      IsInternational: false,
      NeedSpecialTreatment: false,
      ValueType: 'Array',
      Description: '入参',
      PropertyEditor: {
        PropertyEditorType: 113,
        ConfigJSON: null,
      },
      DefaultValue: '',
      IsRequired: false,
      PropType: 1,
      Level: 0,
      ParentID: null,
      ShowValue: '',
      Value: '',
      DisplayName: '',
    },
  ],
  Events: [],
  Methods: [
    {
      ID: '45480772-09ea-f7ba-8606-803581d98149',
      Name: 'Refresh',
      Description: '数据刷新',
      ValueType: 'String',
      Parameters: [],
      IsRequired: 0,
      IsDisplay: 1,
    },
    {
      ID: '460042c2-c7d5-d3c2-9072-f8ab787fe5e4',
      Name: 'Style',
      Description: '样式',
      ValueType: 'String',
      Parameters: [],
      IsRequired: 0,
      IsDisplay: 1,
    },
    {
      ID: 'dec85f5a-e9c8-bfb3-b9bf-4e2b0984f9ab',
      Name: 'AddClass',
      Description: '添加样式',
      ValueType: 'String',
      Parameters: [],
      IsRequired: 0,
      IsDisplay: 1,
    },
    {
      ID: '15b15543-52a5-549c-286a-f6c0db31d889',
      Name: 'RemoveClass',
      Description: '移除样式',
      ValueType: 'String',
      Parameters: [],
      IsRequired: 0,
      IsDisplay: 1,
    },
    {
      ID: 'ac1c1c7e-11c0-f29e-7545-8a7bf1afebdf',
      Name: 'ToggleClass',
      Description: '添加样式',
      ValueType: 'String',
      Parameters: [],
      IsRequired: 0,
      IsDisplay: 1,
    },
  ],
  CompID: '',
  CompName: '门户部件',
  Tag: 'fas-portlet',
  DeviceType: ['pc', 'mobile'],
  ToolboxGroup: '通用组件',
  options: {
    instanceCode: 'NewInstanceID()',
    hideLabel: true,
    visible: true,
    style: '',
    target: '',
    title: '',
    isShowToolsbar: false,
    isShowRefreshButton: false,
    isAutoRefresh: false,
    refreshInterval: 1,
    relation: [],
  },
  type: 'fas',
  name: '门户部件',
  versionCheck: true,
};
export const preparePortal=function(PageID) {
  if(!window.getDataSync) return
  let sgUrl = window.FrameSGHost + 'FASR-GetAccessiblePortalInstances&fasdevappid=' + window.getFasDevAppId();
  let postData = {
      PageID: PageID,//window.pageMetaData.MetaDataID,
      PortalInstanceType: '-1',
      SubSystemCode: window.getFasDevAppId(),
      IsGetDetail: true,
      FilterUserID: true,
      IsGetPortPageMetaData: false
  };
  window.getDataSync(sgUrl, "post", { filter: JSON.stringify(postData) }, (result) => {
      if (result) {
          // this.portalInstanceList = result.data.filter(item=>item.PortalComponentCode == this.element.InstanceCode)
          // this.curPortalInstance = this.portalInstanceList.filter;
          window.portalInstanceGroup = _.chain(result.data).groupBy("PortalComponentCode").value();
      }
  });
}